/**
 * click-accessible.js
 * @author zhangxinxu(.com)
 * @description 检测点击区域过小的元素，仅适合事件底层使用 addEventListener API 的场景
 * @createtime 2022-05-30
 */

 var clickAccessible = (function () {
    if (HTMLElement.prototype.getEventListener) {
        return;
    }
    // 代理 addEventListener
    var originAddEventListener = HTMLElement.prototype.addEventListener;
    HTMLElement.prototype.addEventListener = function (type, listener, options) {
        // 记住相关的时间
        if (!this.allEventListener) {
            this.allEventListener = {};
        }
        if (type && listener) {
            if (!this.allEventListener[type]) {
                this.allEventListener[type] = [listener];
            } else {
                this.allEventListener[type].push(listener);
            }
        }

        return originAddEventListener.call(this, type, listener, options);
    };

    HTMLElement.prototype.hasEventListener = function (type) {
        return Boolean(type && this.allEventListener && this.allEventListener[type]);
    };

    HTMLElement.prototype.getEventListener = function (type) {
        var fn = type && this.allEventListener && this.allEventListener[type];
        return fn || null;
    };

    if (!window.getEventListeners) {
        window.getEventListeners = function (ele) {
            return ele.allEventListener;
        };
    }

    var params= {
        sizeFine: 24,
        sizeCoarse: 40,
        length: 0
    };

    // 判断可点击区域是否过小的问题
    window.addEventListener('DOMContentLoaded', function () {
        [].slice.call(document.all).forEach(function (ele) {
            if (ele.hasEventListener('click') && !ele.disabled) {
                // 判断体积
                var offsetWidth = ele.offsetWidth;
                var offsetHeight = ele.offsetHeight;
                // 大小
                var size = params.sizeFine;
                if (matchMedia('pointer: coarse').matches) {
                    size = params.sizeCoarse;
                }

                if (offsetWidth && offsetHeight && (offsetWidth < size || offsetHeight < size)) {
                    ele.style.outline = 'solid red';
                    params.length += 1;
                }
            }
        });

        if (params.length === 0) {
            console.log('没有不符合要求的的点击尺寸');
        }
    });

    return params;
})();
